#include "autokeypress.h"
#include <QtConcurrent>
#include <QDebug>
#include <QElapsedTimer>

#include <windows.h>
#include <iostream>
#include <chrono>

#include <QDateTime>

#define LOG_INFO() qDebug()<< QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss zzz") << Q_FUNC_INFO << __LINE__

// 检查鼠标左键是否按下
bool isLeftMouseButtonDown()
{
    return (GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0;
}

// 模拟按下F7键
void simulateF7KeyPress()
{
    keybd_event(VK_F7, 0, 0, 0);  // 按下F7
    keybd_event(VK_F7, 0, KEYEVENTF_KEYUP, 0);  // 释放F7
}

bool isF7Pressed = false;

std::atomic<bool> bExited = false;
std::atomic<bool> bChecked = false;
std::atomic<int> threshold = 200;
AutoKeyPress::AutoKeyPress(QObject *parent)
    : QObject{parent}
{
    QtConcurrent::run(QThreadPool::globalInstance(), [&](){
        while(!bExited)
        {
            while(bChecked)
            {
                if (isLeftMouseButtonDown())
                {
                    auto start = std::chrono::high_resolution_clock::now();
                    while (isLeftMouseButtonDown())
                    {
                        auto now = std::chrono::high_resolution_clock::now();
                        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count();
                        if (duration >= threshold)
                        {
                            if (!isF7Pressed)
                            {
                                simulateF7KeyPress();
                                isF7Pressed = true;
                                LOG_INFO()<< "开启即时音量降低";
                            }
                            break;
                        }
                        QThread::msleep(10);  // 减少CPU占用
                    }
                }
                else
                {
                    if (isF7Pressed)
                    {
                        simulateF7KeyPress();
                        isF7Pressed = false;
                        LOG_INFO()<< "关闭即时音量降低";
                    }
                }

                QThread::msleep(10);  // 减少CPU占用
            }
            // 退出时确保F7键被释放
            if (isF7Pressed)
            {
                simulateF7KeyPress();
                isF7Pressed = false;
                LOG_INFO()<< "关闭即时音量降低";
            }
        }
    });
}

AutoKeyPress::~AutoKeyPress()
{
    bChecked = false;
    bExited = true;

    // 退出时确保F7键被释放
    if (isF7Pressed)
    {
        simulateF7KeyPress();
        LOG_INFO()<< "关闭即时音量降低";
    }
}

void AutoKeyPress::setBChecked(bool checked)
{
    bChecked = checked;
}

void AutoKeyPress::setThreshold(int ms)
{
    threshold.store(ms);
}
